//
//  TestFormViewController.swift
//  xiaoqiao
//
//  Created by 冷子豪 on 2017/7/6.
//  Copyright © 2017年 冷子豪. All rights reserved.
//

import UIKit

let dateFormatter = DateFormatter()

class TestFormViewController: UITableViewController {
    // 确定选择哪一个
    var picked:String = ""
    
    var areaPickerView: AreaPickerView?
    // 显示城市
    @IBOutlet weak var cityTextField: UITextField!
    
    // 显示 学历
    @IBOutlet weak var eduTextField: UITextField!
    // 选择 学历
    @IBAction func eduSelector(_ sender: UITextField) {
        picked = "edu"
        // configure pickerView type and the title with the initializer
        let pickerView = TTADataPickerView(title: "", type: .text, delegate: self)
        // configure the delegate
        pickerView.delegate = self
        // when the pickerView type is .text, configure this property to tell the pickerView what you want to select
        pickerView.textItemsForComponent = [["研究生及以上", "本科", "专科", "高中及以下"]]
        // call show() or show(with completion: (() -> Void)? = nil) to show the pickerView from the bottom of the screen
        pickerView.show()
    }
    // 显示 单位性质
    @IBOutlet weak var companyTextField: UITextField!
    @IBAction func companyPicker(_ sender: Any) {
        picked = "com"
        // configure pickerView type and the title with the initializer
        let pickerView = TTADataPickerView(title: "", type: .text, delegate: self)
        // configure the delegate
        pickerView.delegate = self
        // when the pickerView type is .text, configure this property to tell the pickerView what you want to select
        pickerView.textItemsForComponent = [["机关单位", "国有企业", "外商独资", "中外合资", "上市公司", "三资", "社会团体", "个体", "其他"]]
        // call show() or show(with completion: (() -> Void)? = nil) to show the pickerView from the bottom of the screen
        pickerView.show()
    }
    // 职位
    @IBOutlet weak var positionTextField: UITextField!
    @IBAction func positionPicker(_ sender: UITextField) {
        picked = "pos"
        // configure pickerView type and the title with the initializer
        let pickerView = TTADataPickerView(title: "", type: .text, delegate: self)
        // configure the delegate
        pickerView.delegate = self
        // when the pickerView type is .text, configure this property to tell the pickerView what you want to select
        pickerView.textItemsForComponent = [["基层员工", "初级管理者", "中级管理者", "高级管理者", "法人或股东"]]
        // call show() or show(with completion: (() -> Void)? = nil) to show the pickerView from the bottom of the screen
        pickerView.show()
    }
    
    // 工作时间
    @IBOutlet weak var startDateTextField: UITextField!
    @IBAction func startDatePicker(_ sender: UITextField) {
        picked = "start"
        let pickerView = TTADataPickerView(title: "", type: .date, delegate: nil)
        
        // Set `minimumDate` and `maximumDate`
        pickerView.minimumDate = Date(timeIntervalSince1970: -24 * 60 * 60 * 25567)
        pickerView.maximumDate = Date(timeIntervalSinceNow: 0)
        
        pickerView.delegate = self
        pickerView.show {
            UIView.animate(withDuration: 0.3, animations: {
                self.view.backgroundColor = UIColor(white: 1.0, alpha: 0.96)
            })
        }
    }
    
    // 入职时间
    @IBOutlet weak var hireDateTextField: UITextField!
    @IBAction func hireDatePicker(_ sender: UITextField) {
        picked = "hire"
        let pickerView = TTADataPickerView(title: "", type: .date, delegate: nil)
        
        // Set `minimumDate` and `maximumDate`
        pickerView.minimumDate = Date(timeIntervalSince1970: -24 * 60 * 60 * 25567)
        pickerView.maximumDate = Date(timeIntervalSinceNow: 0)
        
        pickerView.delegate = self
        pickerView.show {
            UIView.animate(withDuration: 0.3, animations: {
                self.view.backgroundColor = UIColor(white: 1.0, alpha: 0.96)
            })
        }
    }
    
    // 家庭月收入
    @IBOutlet weak var homeIncomeTextField: UITextField!
    
    // 婚姻状况
    @IBOutlet weak var marryTextField: UITextField!
    @IBAction func marryPicker(_ sender: UITextField) {
        picked = "marry"
        // configure pickerView type and the title with the initializer
        let pickerView = TTADataPickerView(title: "", type: .text, delegate: self)
        // configure the delegate
        pickerView.delegate = self
        // when the pickerView type is .text, configure this property to tell the pickerView what you want to select
        pickerView.textItemsForComponent = [["已婚", "未婚", "离异","其他"]]
        // call show() or show(with completion: (() -> Void)? = nil) to show the pickerView from the bottom of the screen
        pickerView.show()
        
    }
    // 子女个数
    @IBOutlet weak var childTextField: UITextField!
    @IBAction func childPicker(_ sender: UITextField) {
        picked = "child"
        // configure pickerView type and the title with the initializer
        let pickerView = TTADataPickerView(title: "", type: .text, delegate: self)
        // configure the delegate
        pickerView.delegate = self
        // when the pickerView type is .text, configure this property to tell the pickerView what you want to select
        pickerView.textItemsForComponent = [["0", "1", "2", "3个及以上"]]
        // call show() or show(with completion: (() -> Void)? = nil) to show the pickerView from the bottom of the screen
        pickerView.show()
    }
    
    // 房产信息
    @IBOutlet weak var houseTypeTextField: UITextField!
    @IBOutlet weak var housePayTypeLabel: UILabel!
    @IBOutlet weak var housePayTextField: UITextField!
    
    @IBAction func housePicker(_ sender: UITextField) {
        picked = "house"
        // configure pickerView type and the title with the initializer
        let pickerView = TTADataPickerView(title: "", type: .text, delegate: self)
        // configure the delegate
        pickerView.delegate = self
        // when the pickerView type is .text, configure this property to tell the pickerView what you want to select
        pickerView.textItemsForComponent = [["全款房", "按揭房"]]
        // call show() or show(with completion: (() -> Void)? = nil) to show the pickerView from the bottom of the screen
        pickerView.show()
    }
    // 车产信息
    
    @IBOutlet weak var vehicleTypeTextField: UITextField!
    @IBOutlet weak var vehiclePayTypeLabel: UILabel!
    @IBOutlet weak var vehiclePayTextField: UITextField!
    
    @IBAction func vehiclePicker(_ sender: UITextField) {
        picked = "vehicle"
        // configure pickerView type and the title with the initializer
        let pickerView = TTADataPickerView(title: "", type: .text, delegate: self)
        // configure the delegate
        pickerView.delegate = self
        // when the pickerView type is .text, configure this property to tell the pickerView what you want to select
        pickerView.textItemsForComponent = [["全款车", "按揭车"]]
        // call show() or show(with completion: (() -> Void)? = nil) to show the pickerView from the bottom of the screen
        pickerView.show()
    }
    @IBAction func submitTest(_ sender: UIBarButtonItem) {
        // 储存表单中数据
        // id
//        theUser.id = nil
        // 用户id
        theUser.userid = user.id
        // 性别
        theUser.sex = user.sex
        // 年龄
//        theUser.age = nil
        // 城市
        theUser.cityofinfo = cityTextField.text?.trimmingCharacters(in: NSCharacterSet.whitespaces)
//        print(theUser.cityofinfo)
//        print(myLocate.province)
//        print(myLocate.city)
//        print(myLocate.area)
        // 收入
//        theUser.income = 
        // 家庭收入
        theUser.incomeOfHome = homeIncomeTextField.text?.trimmingCharacters(in: NSCharacterSet.whitespaces)
        // 婚姻
        theUser.marriage = marryTextField.text?.trimmingCharacters(in: NSCharacterSet.whitespaces)
        // 健康
//        theUser.health = 
        // 学历
        theUser.education = eduTextField.text?.trimmingCharacters(in: NSCharacterSet.whitespaces)
        // 子女
        if let num = Int((childTextField.text?.trimmingCharacters(in: NSCharacterSet.whitespaces))!){
            theUser.countOfChildren = num
        } else {
            theUser.countOfChildren = 3
        }
        // 住宅（地址）
//        theUser.house_id = nil
        // 车辆
//        theUser.vehicle_id = nil
        // 工作单位
        theUser.companyOfNature = companyTextField.text?.trimmingCharacters(in: NSCharacterSet.whitespaces)
            // 日期格式
        let dateformatter = DateFormatter()
        dateformatter.dateFormat = "MMM dd,yyyy"
        // 开始工作时间
        var timeStr = startDateTextField.text?.trimmingCharacters(in: NSCharacterSet.whitespaces)
        theUser.startOfWork = dateformatter.date(from: timeStr!)
        // 入职时间
        timeStr = hireDateTextField.text?.trimmingCharacters(in: NSCharacterSet.whitespaces)
        theUser.hiredate = dateformatter.date(from: timeStr!)
        // 工作年限
//        theUser.ageOfWork =
        // 职位
        theUser.position = positionTextField.text?.trimmingCharacters(in: NSCharacterSet.whitespaces)
        // 专业技能
//        theUser.professionalSkill = nil
        // 银行账户
//        theUser.stateOfbankOfCount = nil
        // 社保信息
//        theUser.stateOfSheBao = nil
        // 信用卡
//        theUser.creditCard = nil
        // 担保
//        theUser.guarantee = nil
        // 法律诉讼
//        theUser.litigation = nil
        // 贷款记录
//        theUser.loan = nil
        // 通讯录
//        theUser.contactsOfFriends = nil
        // 投资用途
//        theUser.investmentUse = nil
        // 网购记录
//        theUser.onlineShoppingRecord = nil
        // 个人征信查询
//        theUser.personalCreditInquiry = nil
        // 配偶
//        theUser.wife = nil
        // 预估额度
//        theUser.estimatedLoan = nil
        // 状态
        theUser.status = "正常"
        // 创建时间
        if theUser.createtime == nil{
            theUser.createtime = Date()
        }
        // 更新时间
        theUser.updatetime = Date()
        
        _ = theUser.estimateLoan()
        
        
        
        
        // 执行 segue 跳转界面
        performSegue(withIdentifier: "form2test", sender: self)
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //MARK:- 选择器begin
        // config the TTADataPickerView's apperance
        let apperance = TTADataPickerView.appearance()
        apperance.setConfirmButtonAttributes(att: [NSForegroundColorAttributeName: UIColor.darkGray])
        apperance.setCancelButtonAttributes(att: [NSForegroundColorAttributeName: UIColor.darkGray])
        apperance.setToolBarTintColor(color: .lightGray)
        apperance.setToolBarBarTintColor(color: UIColor(white: 0.9, alpha: 0.5))
        apperance.setTitleFont(font: UIFont.systemFont(ofSize: 14))
        apperance.setTitleColor(color: UIColor(colorLiteralRed: 0.0, green: 0.5, blue: 1.0, alpha: 1.0))
        
        
        //MARK:- 选择器end
        
        //MARK:- 地区选择器begin
        //初始化地址(如果有),方便弹出pickerView后能够主动选中,这时候还没有区域代码信息,但是只要一划动并确定就有了.理论上进入地址控制器时候,要么全部信息有,要么全部信息没有....我先赋值只是为了演示功能.
        myLocate.province = ""
        myLocate.city = ""
        myLocate.area = ""
        setAreaText(locate: myLocate)
        
        //areaPickerView.有控制器在的时候,不会被销毁.跟控制器时间销毁...没关系吧?
        areaPickerView = AreaPickerView.picker(for: self, textField: cityTextField)
        cityTextField.delegate = self  //也个也最好实现.因为可以在将要显示PickerView的时候,主动选中一个地区.
        
        //为了点击空白的时候能够退键盘
        let tapGR = UITapGestureRecognizer(target: self, action: #selector(viewDidTap(tapGR:)))
        tapGR.cancelsTouchesInView = false
        view.addGestureRecognizer(tapGR)
        //MARK:- 地区选择器end
        
        //MARK:- 文本框初始值
        let formatter = DateFormatter()
        formatter.dateFormat = "MMM dd,yyyy"

        // 城市
        cityTextField.text = theUser.cityofinfo
        eduTextField.text = theUser.education
        companyTextField.text = theUser.companyOfNature
        positionTextField.text = theUser.position
        if(theUser.startOfWork != nil){
            startDateTextField.text = formatter.string(from: theUser.startOfWork!)
        } else {
//            startDateTextField.text = "无初始值"
        }
        if(theUser.startOfWork != nil){
            hireDateTextField.text = formatter.string(from: theUser.hiredate!)
        }
        homeIncomeTextField.text = theUser.incomeOfHome
        marryTextField.text = theUser.marriage
        // 子女个数
        if theUser.countOfChildren == 3{
            childTextField.text = "3个及以上"
        } else if theUser.countOfChildren == nil{
            childTextField.text = ""
        } else {
            childTextField.text = "\(String(describing: theUser.countOfChildren))"
        }
//        
//        houseTypeTextField.text =
//        housePayTextField.text =
//        vehicleTypeTextField.text =
//        vehiclePayTypeLabel.text =
    }
    
    func viewDidTap(tapGR: UITapGestureRecognizer) {
        view.endEditing(true)
    }
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    // MARK: - lazy
    lazy var myLocate: Location = {
        return Location()
    }()
    
}

extension TestFormViewController: UITextFieldDelegate {
    
    //主动选择某一个地区,主动弹出某个区域以选中....
    func textFieldDidBeginEditing(_ textField: UITextField) {
        areaPickerView?.shouldSelected(proName: myLocate.province, cityName: myLocate.city, areaName: myLocate.area)
    }
}

extension TestFormViewController: AreaPickerDelegate {
    internal func cancel(areaToolbar: AreaToolbar, textField: UITextField, locate: Location, item: UIBarButtonItem) {
        print("点击了取消")
        //还原原来的值......
        myLocate.decription()
        setAreaText(locate: myLocate)
    }
    
    internal func sure(areaToolbar: AreaToolbar, textField: UITextField, locate: Location, item: UIBarButtonItem) {
        print("点击了确定")
        //当picker定住的时候,就有会值.**********但是******************
        //picker还有转动的时候有些值是空的........取值前一定要判断是否为空.否则crash.....
        //赋值新地址......
        print("最后的值是\n")
        locate.decription()
        //        myLocate = locate //不能直接赋值地址,这个是引用来的
        myLocate.province = locate.province
        myLocate.provinceCode = locate.provinceCode
        myLocate.city = locate.city
        myLocate.cityCode = locate.cityCode
        myLocate.area = locate.area
        myLocate.areaCode = locate.areaCode
        
    }
    
    internal func statusChanged(areaPickerView: AreaPickerView, pickerView: UIPickerView, textField: UITextField, locate: Location) {
        //立即显示新值
        print("转到的值:\n")
        locate.decription()
        if !locate.area.isEmpty {
            textField.text = "\(locate.province) \(locate.city) \(locate.area)"
        } else {
            textField.text = "\(locate.province) \(locate.city)"
        }
    }
    
    
    func setAreaText(locate: Location) {
        var areaText = ""
        if locate.city.isEmpty {
            areaText = locate.province
        } else if locate.area.isEmpty {
            areaText = "\(locate.province) \(locate.city)"
        } else {
            areaText = "\(locate.province) \(locate.city) \(locate.area)"
        }
        cityTextField.text = areaText
    }
    
}
// MARK: - TTADataPickerViewDelegate

extension TestFormViewController: TTADataPickerViewDelegate {
    // when the pickerView type is `.text`, you clicked the done button, you will get the titles you selected just now from the `titles` parameter
    func dataPickerView(_ pickerView: TTADataPickerView, didSelectTitles titles: [String]) {
        switch picked {
        case "edu":
            eduTextField.text = titles.joined(separator: " ")
        case "com":
            companyTextField.text = titles.joined(separator: " ")
        case "pos":
            positionTextField.text = titles.joined(separator: " ")
        case "marry":
            marryTextField.text = titles.joined(separator: " ")
        case "child":
            childTextField.text = titles.joined(separator: " ")
        case "house":
            let pickedType = titles.joined(separator: " ")
            houseTypeTextField.text = pickedType
            if pickedType == "全款房"{
                housePayTypeLabel.text = "现价值："
                housePayTextField.placeholder = "请输入（元）"
            } else {
                housePayTypeLabel.text = "月供："
                housePayTextField.placeholder = "请输入（元/月）"
            }
        case "vehicle":
            let pickedType = titles.joined(separator: " ")
            vehicleTypeTextField.text = pickedType
            if pickedType == "全款车"{
                vehiclePayTypeLabel.text = "现价值："
                vehiclePayTextField.placeholder = "请输入（元）"
            } else {
                vehiclePayTypeLabel.text = "月供："
                vehiclePayTextField.placeholder = "请输入（元/月）"
            }
        default:
            print("默认")
        }
    }
    // when the pickerView type is NOT `.text`, you clicked the done button, you will get the date you selected just now from the `date` parameters
    func dataPickerView(_ pickerView: TTADataPickerView, didSelectDate date: Date) {
        // actually you need configure the dateFormatter dateStyle and timeStyle to get the currect date from the `date` parameter
        if pickerView.type == .date {
            dateFormatter.dateStyle = .medium
            dateFormatter.timeStyle = .none
        } else if pickerView.type == .time {
            dateFormatter.timeStyle = .medium
            dateFormatter.dateStyle = .none
        } else if pickerView.type == .dateTime {
            dateFormatter.dateStyle = .medium
            dateFormatter.timeStyle = .medium
        }
        //eduTextField.text = dateFormatter.string(from: date)
        switch picked {
        case "start":
            startDateTextField.text = dateFormatter.string(from: date)
        case "hire":
            hireDateTextField.text = dateFormatter.string(from: date)
        default:
            print("默认")
        }
    }
    // when the pickerView  has been changed, this function will be called, and you will get the row and component which changed just now
    func dataPickerView(_ pickerView: TTADataPickerView, didChange row: Int, inComponent component: Int) {
        print(#function)
    }
    // when you clicked the cancel button, this function will be called firstly
    func dataPickerViewWillCancel(_ pickerView: TTADataPickerView) {
        print(#function)
    }
    // when you clicked the cancel button, this function will be called at the last
    func dataPickerViewDidCancel(_ pickerView: TTADataPickerView) {
        print(#function)
    }
}
